package com.mf.service.impl;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName: SocketService
 * Package: com.mf.service
 * Description:
 *
 * @Author: lmf
 * @Create: 2024/5/6 10:03
 * @Version: 1.0
 */

@Service
public class SocketService {
    private ServerSocket serverSocket;
    private List<Socket> clientSockets = new ArrayList<>();

    private ExecutorService executorService;

    @PostConstruct
    public void startServerSocket() throws IOException {
        serverSocket = new ServerSocket(12345);
        System.out.println("Server Socket started on port 12345");

        new Thread(() -> {
            while (!serverSocket.isClosed()) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("New client connected.");
                    clientSockets.add(clientSocket);

                    // 为每个客户端连接启动一个新的线程
                    new Thread(() -> handleClient(clientSocket)).start();
                } catch (IOException e) {
                    e.printStackTrace();
                    break; // 发生错误时关闭服务器套接字
                }
            }
        }).start();
    }

    private void handleClient(Socket clientSocket) {
        try {
            // 创建PrintWriter用于向客户端发送消息
            PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

            // 读取客户端发送的消息的线程（如果需要的话）
            // 你可以在这里实现消息的读取和响应逻辑
            // new Thread(() -> {
            //     // 读取消息的代码
            // }).start();

            // 当用户调用 /get 请求时，向客户端发送消息
            // 实际应用中，你可能需要使用某种机制（如Spring的@EventListener）来监听/get请求
            // 这里只是模拟发送消息给所有客户端
            sendMessageToAllClients("Message from server");

            // 保持连接打开，以便能够长期接收客户端消息
            // 不要在这里关闭clientSocket

        } catch (IOException e) {
            e.printStackTrace();
            // 如果发生错误，则从列表中移除并关闭Socket
            clientSockets.remove(clientSocket);
            try {
                clientSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void sendMessageToAllClients(String message) {
        System.out.println("发送消息"+message);
        for (Socket socket : clientSockets) {
            System.out.println(socket.toString());
            try {
                PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
                writer.println(message);
            } catch (IOException e) {
                // 处理异常，例如客户端断开连接等
                e.printStackTrace();
                clientSockets.remove(socket);
                try {
                    socket.close();
                } catch (IOException ex) {
                    // Log or handle the exception as needed
                }
            }
        }
    }
    @PreDestroy
    public void stopServerSocket() throws IOException {
        if (serverSocket != null && !serverSocket.isClosed()) {
            serverSocket.close();
        }
        for (Socket clientSocket : clientSockets) {
            try {
                clientSocket.close();
            } catch (IOException e) {
                // Log or handle the exception as needed
            }
        }
        System.out.println("Server Socket stopped");
    }
}
